<template>
  <div class="chat-page">
    <!-- 顶部栏 -->
    <div class="header">
      <div class="header-left">
        <el-button
          type="text"
          @click="goBack"
          class="back-btn"
        >
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <div class="app-info">
          <h2 class="app-name">{{ appInfo.appName || '应用对话' }}</h2>
          <span class="app-id">ID: {{ appId }}</span>
        </div>
      </div>
      <div class="header-actions">
        <el-button
          type="primary"
          :loading="deployLoading"
          @click="deployApp"
          :disabled="!canDeploy"
        >
          <el-icon><Upload /></el-icon>
          {{ deployLoading ? '部署中...' : '部署应用' }}
        </el-button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧对话区域 -->
      <div class="chat-section">
        <!-- 消息区域 -->
        <div class="messages-container" ref="messagesContainer">
          <div
            v-for="message in messages"
            :key="message.id"
            :class="['message-item', message.role]"
          >
            <div class="message-avatar">
              <el-avatar
                v-if="message.role === 'user'"
                :src="loginUserStore.loginUser.userAvatar"
                :icon="UserFilled"
                :size="32"
              />
              <el-avatar
                v-else
                :size="32"
                class="ai-avatar"
              >
                <el-icon><ChatDotRound /></el-icon>
              </el-avatar>
            </div>
            <div class="message-content">
              <div class="message-text">
                <div v-if="message.role === 'assistant' && message.streaming" class="streaming-text">
                  {{ message.content }}
                  <span class="cursor">|</span>
                </div>
                <div v-else v-html="formatMessage(message.content)"></div>
              </div>
              <div class="message-time">{{ formatTime(message.createTime) }}</div>
            </div>
          </div>

          <!-- AI正在输入指示器 -->
          <div v-if="isAiTyping" class="message-item assistant">
            <div class="message-avatar">
              <el-avatar :size="32" class="ai-avatar">
                <el-icon><ChatDotRound /></el-icon>
              </el-avatar>
            </div>
            <div class="message-content">
              <div class="message-text">
                <div class="typing-indicator">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 用户消息输入框 -->
        <div class="input-section">
          <div class="input-container">
            <el-input
              v-model="userInput"
              type="textarea"
              :rows="3"
              placeholder="请输入您的需求，描述想要的功能或修改..."
              class="message-input"
              @keydown.ctrl.enter="sendMessage"
              :disabled="isAiTyping"
            />
            <div class="input-actions">
              <div class="input-tips">
                <span>Ctrl + Enter 发送</span>
              </div>
              <el-button
                type="primary"
                @click="sendMessage"
                :loading="isAiTyping"
                :disabled="!userInput.trim() || isAiTyping"
              >
                <el-icon><Position /></el-icon>
                发送
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧网页展示区域 -->
      <div class="preview-section">
        <div class="preview-header">
          <h3>网页预览</h3>
          <div class="preview-actions">
            <el-button
              size="small"
              @click="refreshPreview"
              :disabled="!hasGeneratedCode"
            >
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
            <el-button
              size="small"
              @click="openInNewTab"
              :disabled="!hasGeneratedCode"
            >
              <el-icon><View /></el-icon>
              新窗口打开
            </el-button>
          </div>
        </div>

        <div class="preview-container">
          <div v-if="!hasGeneratedCode" class="preview-placeholder">
            <el-empty description="开始对话生成网页代码后，这里将显示预览效果">
              <el-icon class="placeholder-icon"><Monitor /></el-icon>
            </el-empty>
          </div>

          <iframe
            v-else
            ref="previewFrame"
            :src="previewUrl"
            class="preview-iframe"
            @load="onPreviewLoad"
          ></iframe>

          <div v-if="previewLoading" class="preview-loading">
            <el-loading-directive v-loading="true" text="加载预览中..." />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft,
  Upload,
  UserFilled,
  Position,
  Refresh,
  View,
  Monitor,
  ChatDotRound
} from '@element-plus/icons-vue'
import { useLoginUserStore } from '@/stores/loginUser'
import api from '@/api'

const route = useRoute()
const router = useRouter()
const loginUserStore = useLoginUserStore()

// 路由参数
const appId = computed(() => route.params.id)

// 应用信息
const appInfo = ref<API.AppVO>({})
const deployLoading = ref(false)

// 消息列表
const messages = ref<any[]>([])
const userInput = ref('')
const isAiTyping = ref(false)
const messagesContainer = ref<HTMLElement>()

// 预览相关
const hasGeneratedCode = ref(false)
const previewUrl = ref('')
const previewLoading = ref(false)
const previewFrame = ref<HTMLIFrameElement>()
const canDeploy = ref(false)

// 返回上一页
const goBack = () => {
  router.back()
}

// 初始化
onMounted(async () => {
  if (appId.value) {
    await loadAppInfo()
    await loadChatHistory()

    // 如果是新创建的应用，自动发送初始提示词
    if (route.query.autoStart === 'true' && appInfo.value.initPrompt) {
      await sendInitialMessage()
    }
  }
})

// 加载应用信息
const loadAppInfo = async () => {
  try {
    const response = await api.appController.getAppVoById({ id: parseInt(appId.value as string) })
    if (response.data.code === 0 && response.data.data) {
      appInfo.value = response.data.data
    }
  } catch (error) {
    console.error('加载应用信息失败:', error)
    ElMessage.error('加载应用信息失败')
  }
}

// 加载聊天历史
const loadChatHistory = async () => {
  try {
    // TODO: 实现聊天历史加载API
    // const response = await chatApi.getChatHistory(appId.value)
    // if (response.code === 0) {
    //   messages.value = response.data || []
    //   await nextTick()
    //   scrollToBottom()
    // }
    messages.value = []
  } catch (error) {
    console.error('加载聊天历史失败:', error)
  }
}

// 发送初始消息
const sendInitialMessage = async () => {
  if (!appInfo.value.initPrompt) return

  // 添加用户消息
  const userMessage = {
    id: Date.now(),
    role: 'user',
    content: appInfo.value.initPrompt,
    createTime: new Date().toISOString()
  }
  messages.value.push(userMessage)

  await nextTick()
  scrollToBottom()

  // 开始AI对话
  await startAiChat(appInfo.value.initPrompt)
  // 将路由上的参数 autoStart 设为 false
  await router.replace({
    path: `/chat/${appId.value}`,
    query: {
      ...route.query,
      autoStart: 'false'
    }
  })
}

// 发送消息
const sendMessage = async () => {
  if (!userInput.value.trim() || isAiTyping.value) return

  const content = userInput.value.trim()
  userInput.value = ''

  // 添加用户消息
  const userMessage = {
    id: Date.now(),
    role: 'user',
    content,
    createTime: new Date().toISOString()
  }
  messages.value.push(userMessage)

  await nextTick()
  scrollToBottom()

  // 开始AI对话
  await startAiChat(content)
}

// 开始AI对话（SSE流式）
const startAiChat = async (content: string) => {
  isAiTyping.value = true

  // 添加AI消息占位符
  const aiMessage = {
    id: Date.now() + 1,
    role: 'assistant',
    content: '',
    streaming: true,
    createTime: new Date().toISOString()
  }
  messages.value.push(aiMessage)

  // 获取当前消息在数组中的索引，用于后续更新
  const messageIndex = messages.value.length - 1

  try {
    // 创建SSE连接，需要手动处理cookie传递
    // EventSource不支持自定义headers，所以需要在URL中传递token
    const token = document.cookie.split('; ').find(row => row.startsWith('satoken='))?.split('=')[1]
    const eventSource = new EventSource(
      `http://localhost:10081/api/app/chat/gen/code?appId=${appId.value}&message=${encodeURIComponent(content)}&satoken=${token || ''}`
    )

    eventSource.onmessage = async (event) => {
      try {
        // 解析后端返回的JSON格式数据 {"d": chunk}
        const data = JSON.parse(event.data)
        if (data.d) {
          // 通过索引直接更新messages数组中的内容，确保响应式更新
          messages.value[messageIndex].content += data.d
          await nextTick()
          scrollToBottom()
        }
      } catch (error) {
        console.error('解析SSE数据失败:', error)
        // 如果解析失败，尝试直接使用原始数据
        messages.value[messageIndex].content += event.data
        await nextTick()
        scrollToBottom()
      }
    }

    eventSource.onopen = () => {
      console.log('SSE连接已建立')
    }

    // 监听'done'事件，表示流式传输完成
    eventSource.addEventListener('done', () => {
      console.log('SSE流式传输完成')
      eventSource.close()
      isAiTyping.value = false

      if (messages.value[messageIndex].content.trim() !== '') {
        messages.value[messageIndex].content += '\n\n代码已生成完成！您可以在右侧预览区域查看效果。'
        hasGeneratedCode.value = true
        canDeploy.value = true
        updatePreview()
      }

      messages.value[messageIndex].streaming = false
    })

    eventSource.onerror = (error) => {
      console.error('SSE连接错误:', error)
      eventSource.close()
      isAiTyping.value = false

      if (messages.value[messageIndex].content.trim() === '') {
        messages.value[messageIndex].content = '抱歉，连接中断，请稍后重试。'
      } else {
        messages.value[messageIndex].content += '\n\n代码已生成完成！您可以在右侧预览区域查看效果。'
        hasGeneratedCode.value = true
        canDeploy.value = true
        updatePreview()
      }

      messages.value[messageIndex].streaming = false
    }

    // 监听连接关闭事件
    eventSource.addEventListener('close', () => {
      console.log('SSE连接已关闭')
      eventSource.close()
      isAiTyping.value = false

      if (messages.value[messageIndex].content.trim() !== '') {
        messages.value[messageIndex].content += '\n\n代码已生成完成！您可以在右侧预览区域查看效果。'
        hasGeneratedCode.value = true
        canDeploy.value = true
        updatePreview()
      }

      messages.value[messageIndex].streaming = false
    })

    // 设置超时 - 增加到10分钟以适应DeepSeek推理模型
    setTimeout(() => {
      if (eventSource.readyState !== EventSource.CLOSED) {
        console.log('SSE连接超时，主动关闭')
        eventSource.close()
        isAiTyping.value = false

        if (messages.value[messageIndex].content.trim() !== '') {
          messages.value[messageIndex].content += '\n\n代码已生成完成！您可以在右侧预览区域查看效果。'
          hasGeneratedCode.value = true
          canDeploy.value = true
          updatePreview()
        } else {
          messages.value[messageIndex].content = '请求超时，请稍后重试。'
        }

        messages.value[messageIndex].streaming = false
      }
    }, 600000) // 10分钟超时

  } catch (error) {
    console.error('发送消息失败:', error)
    messages.value[messageIndex].content = '抱歉，生成代码时出现了错误，请稍后重试。'
    messages.value[messageIndex].streaming = false
    isAiTyping.value = false
    ElMessage.error('发送消息失败')
  }
}

// 更新预览
const updatePreview = () => {
  if (hasGeneratedCode.value) {
    previewUrl.value = `http://localhost:8123/api/static/web_${appId.value}/`
    previewLoading.value = true
  }
}

// 部署应用
const deployApp = async () => {
  if (!hasGeneratedCode.value) {
    ElMessage.warning('请先生成代码')
    return
  }

  try {
    await ElMessageBox.confirm(
      '确定要部署此应用吗？部署后将生成可访问的URL地址。',
      '确认部署',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    deployLoading.value = true
    const response = await api.appController.deployApp({ appId: parseInt(appId.value as string) })

    if (response.data.code === 0 && response.data.data) {
      ElMessage.success('应用部署成功！')

      // 显示部署URL
      await ElMessageBox.alert(
        `部署成功！访问地址：${response.data.data}`,
        '部署完成',
        {
          confirmButtonText: '确定',
          callback: () => {
            window.open(response.data.data, '_blank')
          }
        }
      )
    } else {
      ElMessage.error(response.data.message || '部署失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('部署失败:', error)
      ElMessage.error('部署失败，请重试')
    }
  } finally {
    deployLoading.value = false
  }
}

// 刷新预览
const refreshPreview = () => {
  if (previewFrame.value) {
    previewFrame.value.src = previewFrame.value.src
    previewLoading.value = true
  }
}

// 新窗口打开
const openInNewTab = () => {
  if (previewUrl.value) {
    window.open(previewUrl.value, '_blank')
  }
}

// 预览加载完成
const onPreviewLoad = () => {
  previewLoading.value = false
}

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 格式化消息内容
const formatMessage = (content: string) => {
  // 简单的markdown渲染
  return content
    .replace(/\n/g, '<br>')
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.*?)\*/g, '<em>$1</em>')
    .replace(/`(.*?)`/g, '<code>$1</code>')
}

// 格式化时间
const formatTime = (timeString: string) => {
  if (!timeString) return ''
  const date = new Date(timeString)
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 监听消息变化，自动滚动
watch(messages, () => {
  nextTick(() => {
    scrollToBottom()
  })
}, { deep: true })

// 监听路由变化
watch(() => route.params.id, (newId) => {
  if (newId) {
    messages.value = []
    hasGeneratedCode.value = false
    previewUrl.value = ''
    loadAppInfo()
  }
})
</script>

<style scoped>
.chat-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: white;
  border-bottom: 1px solid #e8e8e8;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.back-btn {
  color: #666;
  font-size: 14px;
}

.app-info {
  display: flex;
  flex-direction: column;
}

.app-name {
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0;
}

.app-id {
  font-size: 12px;
  color: #999;
}

.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.chat-section {
  width: 50%;
  display: flex;
  flex-direction: column;
  background: white;
  border-right: 1px solid #e8e8e8;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
}

.message-item {
  display: flex;
  margin-bottom: 24px;
  align-items: flex-start;
  gap: 12px;
}

.message-item.user {
  flex-direction: row-reverse;
}

.message-item.user .message-content {
  text-align: right;
}

.message-avatar {
  flex-shrink: 0;
}

.ai-avatar {
  background: linear-gradient(45deg, #667eea, #764ba2);
  color: white;
}

.message-content {
  flex: 1;
  max-width: 70%;
}

.message-text {
  background: #f8f9fa;
  padding: 12px 16px;
  border-radius: 12px;
  line-height: 1.6;
  word-wrap: break-word;
}

.message-item.user .message-text {
  background: #667eea;
  color: white;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.streaming-text .cursor {
  animation: blink 1s infinite;
}

@keyframes blink {
  0%, 50% { opacity: 1; }
  51%, 100% { opacity: 0; }
}

.typing-indicator {
  display: flex;
  gap: 4px;
  align-items: center;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #ccc;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) { animation-delay: -0.32s; }
.typing-indicator span:nth-child(2) { animation-delay: -0.16s; }

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.input-section {
  padding: 24px;
  border-top: 1px solid #e8e8e8;
  background: #fafafa;
}

.input-container {
  background: white;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.message-input {
  margin-bottom: 12px;
}

.message-input :deep(.el-textarea__inner) {
  border: none;
  resize: none;
  font-size: 14px;
  line-height: 1.6;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.input-tips {
  font-size: 12px;
  color: #999;
}

.preview-section {
  width: 50%;
  display: flex;
  flex-direction: column;
  background: white;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid #e8e8e8;
  background: #fafafa;
}

.preview-header h3 {
  margin: 0;
  font-size: 16px;
  color: #2c3e50;
}

.preview-actions {
  display: flex;
  gap: 8px;
}

.preview-container {
  flex: 1;
  position: relative;
  overflow: hidden;
}

.preview-placeholder {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f8f9fa;
}

.placeholder-icon {
  font-size: 48px;
  color: #ddd;
  margin-bottom: 16px;
}

.preview-iframe {
  width: 100%;
  height: 100%;
  border: none;
  background: white;
}

.preview-loading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .main-content {
    flex-direction: column;
  }

  .chat-section,
  .preview-section {
    width: 100%;
  }

  .chat-section {
    height: 60vh;
  }

  .preview-section {
    height: 40vh;
    border-right: none;
    border-top: 1px solid #e8e8e8;
  }
}

@media (max-width: 768px) {
  .header {
    padding: 12px 16px;
  }

  .app-name {
    font-size: 18px;
  }

  .messages-container {
    padding: 16px;
  }

  .input-section {
    padding: 16px;
  }

  .message-content {
    max-width: 85%;
  }
}
</style>
